package com.xbfinal.core;

import com.xbfinal.utils.Constant;
import com.xbfinal.utils.HttpUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.util.Collection;
import java.util.RandomAccess;
import java.util.concurrent.Callable;

/**
 * @version 1.0
 * @Author 笑霸final
 * @Date 2023/10/20 13:14
 * @注释 分块下载器
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DownloaderTask implements Callable<Boolean> {

    private String url;

    private long startPost;

    private long startEnd;

    private int part;




    @Override
    public Boolean call() throws Exception {

        //获取文件名
        String httpFileName = HttpUtils.getHttpFileName(url);
        //分块的文件名
        httpFileName +=".temp"+part;
        //下载路径
        httpFileName = Constant.PATH+httpFileName;

        //分块下载的链接
        HttpURLConnection httpUrlConnection = HttpUtils.getHttpUrlConnection(url, startPost, startEnd);


        try(
                InputStream inputStream = httpUrlConnection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                RandomAccessFile randomAccess = new RandomAccessFile(httpFileName,"rw")
        ){

            byte[] buffer = new byte[Constant.BYTE_SIZE];
            int len=-1;
            //循环读取数据
            while ((len =bis.read(buffer)) !=-1){
                //1秒内下载数据之和  (原子类)
                DownloaderInfo.downSize.add(len);
                randomAccess.write(buffer,0,len);
            }

        }catch (FileNotFoundException e){
            System.out.println("文件未找到");
            return false;
        }catch (Exception e){
            System.out.println("未知问题");
            return false;
        }finally {
            httpUrlConnection.disconnect();
        }


        return true;
    }
}
